package com.managertrade.config;

import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class MultiPeriodCache {

    private final ConcurrentHashMap<String, ConcurrentHashMap<String, Object>> periodCaches = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, Object> periodCachesTimes = new ConcurrentHashMap<>();
    public MultiPeriodCache() {
    }

    public boolean checkAndPut(String period, String id) {
        ConcurrentHashMap<String, Object> cache = periodCaches.get(period);
        if (cache == null) {
            periodCaches.put(period, new ConcurrentHashMap<>());
            ConcurrentHashMap<String, Object> cacheCreate = periodCaches.get(period);
            cacheCreate.put(id, true);
            return true;
        }
        if (cache.containsKey(id)) {
            return false;
        }
        cache.put(id, true);
        return true;
    }

    public boolean exists(String period, String id) {
        ConcurrentHashMap<String, Object> cache = periodCaches.get(period);
        return cache != null && cache.containsKey(id);
    }

    public void put(String period,  Object value) {
        Object time = periodCachesTimes.get(period);
        if (time != null) {
            periodCachesTimes.remove(period);
        }
        periodCachesTimes.put(period, value);
    }

    public Object get(String period) {
        Object time = periodCachesTimes.get(period);
        return time != null ? time : null;
    }
}
